//
//  WPRecordViewModel.m
//  health
//
//  Created by apple on 2021/11/9.
//  Copyright © 2021 zglee. All rights reserved.
//

#import "MJHttpNetWorking.h"
#import "MJHttpRequest.h"
#import "MJNetWorking.h"

@implementation MJHttpNetWorking

+ (void)showBaseModel:(MJBaseModel *)model{
    
    NSString *string = @"";
    if([model.data isKindOfClass:[NSDictionary class]]){
        
       string = [(NSDictionary *)model.data mj_dictionaryConvertToString];
    }else if([model.data isKindOfClass:[NSArray class]]){
       string = [(NSArray *)model.data mj_arrayConvertToString];
    }else if([model.data isKindOfClass:[NSString class]]){
        string = model.data;
    }
    
    NSLog(@"return datas=======================%@",[model mj_toDic]);
}

+ (void)httpSuccessBlock:(HttpSuccessBlock)success model:(MJBaseModel *)model showLoading:(BOOL)showLoading  {
    if(showLoading){
        [[WPLoadView shared] closeLoadView];
    }
    if (success) {
        success(model);
        
        if (model.code ==  401){
            [HealthHelper loginExpiredAlertViewWithConfirmBlock:^{
                [UserManager.shared logout];
            } cancelBlock:^{
                
            }];
        }
        
    }else{
        [RoyHud showToast:model.msg];
    }
    
//    NSLog(@"success=======================%@",[model mj_toDic]);
}

+ (void)httpFailureBlock:(HttpFailureBlock)failure error:(NSError *)error showLoading:(BOOL)showLoading{
    
    if(showLoading){
        [[WPLoadView shared] closeLoadView];
    }
    if (failure) {
        failure(error);
    }
    NSLog(@"error=======================%@",error);

}

+ (void)requestWithParams:(NSDictionary *)params
              requestUri:(NSString *)requestUri
              requestType:(MJHttpRequestType)requestType
              showLoading:(BOOL)showLoading
              success:(HttpSuccessBlock)success
              failure:(HttpFailureBlock)failure{
    
    MJHttpNetWorking *viewModel = [[MJHttpNetWorking alloc]init];
    if(showLoading){
        [[WPLoadView shared] showLoadView];
    }
    if(requestType == RequestTypeGet){
        [viewModel mj_getWithSuccess:^(MJBaseModel *model) {
            
            [MJHttpNetWorking httpSuccessBlock:success model:model showLoading:showLoading];
            
        } failure:^(NSError *error) {
            
            [MJHttpNetWorking httpFailureBlock:failure error:error showLoading:showLoading];
        }];
    }

    if(requestType == RequestTypePost){
        [viewModel mj_postBodyWithSuccess:^(MJBaseModel *model) {
            [MJHttpNetWorking httpSuccessBlock:success model:model showLoading:showLoading];

        } failure:^(NSError *error) {
            [MJHttpNetWorking httpFailureBlock:failure error:error showLoading:showLoading];

        }];
    }
    if(requestType == RequestTypePut){
        [viewModel mj_putBodyWithSuccess:^(MJBaseModel *model) {
            [MJHttpNetWorking httpSuccessBlock:success model:model showLoading:showLoading];

        } failure:^(NSError *error) {
            [MJHttpNetWorking httpFailureBlock:failure error:error showLoading:showLoading];

        }];
    }
    if(requestType == RequestTypePutForm){
        [viewModel mj_putWithSuccess:^(MJBaseModel *model) {
            [MJHttpNetWorking httpSuccessBlock:success model:model showLoading:showLoading];

        } failure:^(NSError *error) {
            [MJHttpNetWorking httpFailureBlock:failure error:error showLoading:showLoading];

        }];
    }
    if(requestType == RequestTypeDelete){
        [viewModel mj_deleteWithSuccess:^(MJBaseModel *model) {
            [MJHttpNetWorking httpSuccessBlock:success model:model showLoading:showLoading];

        } failure:^(NSError *error) {
            [MJHttpNetWorking httpFailureBlock:failure error:error showLoading:showLoading];

        }];
    }

    MJHttpRequest * entity = [MJHttpRequest new];
    entity.requestApi = [NSString stringWithFormat:@"%@%@",ServiceUrl,requestUri];
    entity.param = params;
    entity.responseObject = [MJBaseModel class];
    [viewModel.command execute:entity];
    NSLog(@"MJLog=======================%@\nRequestParam===%@",entity.requestApi,entity.param);
}

#pragma mark -
- (void)mj_deleteWithSuccess:(HttpSuccessBlock)seccess failure:(HttpFailureBlock)failure{
    self.command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        //发送
        return [[MJNetWorking createDeleteRequestMenagerWithHttpRequest:input] doNext:seccess];
    }];
    //发送错误
    [self.command.errors subscribeNext:failure];
}

- (void)mj_putWithSuccess:(HttpSuccessBlock)seccess failure:(HttpFailureBlock)failure{
    self.command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        //发送
        return [[MJNetWorking createPutRequestMenagerWithHttpRequest:input] doNext:seccess];
    }];
    //发送错误
    [self.command.errors subscribeNext:failure];
}

- (void)mj_getWithSuccess:(HttpSuccessBlock)seccess failure:(HttpFailureBlock)failure{
    self.command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        //发送
        return [[MJNetWorking createGetRequestMenagerWithHttpRequest:input] doNext:seccess];
    }];
    //发送错误
    [self.command.errors subscribeNext:failure];
}

- (void)mj_postBodyWithSuccess:(HttpSuccessBlock)seccess failure:(HttpFailureBlock)failure{
    self.command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        //发送
        return [[MJNetWorking createPostBodyRequestMenagerWithHttpRequest:input] doNext:seccess];
    }];
    //发送错误
    [self.command.errors subscribeNext:failure];
}

- (void)mj_putBodyWithSuccess:(HttpSuccessBlock)seccess failure:(HttpFailureBlock)failure{
    self.command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        //发送
        return [[MJNetWorking createPutBodyRequestMenagerWithHttpRequest:input] doNext:seccess];
    }];
    //发送错误
    [self.command.errors subscribeNext:failure];
}

#pragma mark -
/// 发送验证码
+ (void)sendPhoneCodeWithPhoneNumber:(NSString *)phoneNumber success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
   
    [MJHttpNetWorking getAuthenticationSuccess:^(MJBaseModel *aModel) {
        
        NSString *aes = aModel.data;
        [MJUIUserDeFault setObject:aes forKey:Authentication];
        [MJHttpNetWorking requestWithParams:@{@"aes":aesEncryptString(aes, kTokenKey)?:@"",@"phone":phoneNumber?:@"",@"uuid":aes} requestUri:SendPhoneCode requestType:RequestTypePost showLoading:true success:^(MJBaseModel *model) {
            
            if(model.code == 200){
                success(model);
            }else{
                [RoyHud showToast:model.msg];
            }

        } failure:^(NSError *error) {
            failure(error);
        }];
            
    } failure:^(NSError * _Nonnull error) {
            
    }];

}

/// 获取鉴权
+ (void)getAuthenticationSuccess:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    [MJHttpNetWorking requestWithParams:@{} requestUri:GetAuthentication requestType:RequestTypeGet showLoading:true success:^(MJBaseModel *model) {
        
        if(model.code == 200){
            success(model);
        }

    } failure:^(NSError *error) {
        failure(error);
    }];
}

+ (void)uploadImageWithParams:(NSDictionary *)params
              requestUri:(NSString *)requestUri
                 image:(UIImage *)image
              showLoading:(BOOL)showLoading
              success:(HttpSuccessBlock)success
                  failure:(HttpFailureBlock)failure{
    
    NSString *requestApi = [NSString stringWithFormat:@"%@%@",ServiceUrl,requestUri];

    
    if(showLoading){
        [[WPLoadView shared] showLoadView];
    }
    
    AFHTTPSessionManager * manager =  [MJNetWorking createManagerIsSynchronous:NO];
    [manager POST:requestApi parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
        // 图片太大会上传不到服务器上面去
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);;
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        // 设置时间格式
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", [[NSDate new] mj_timestampStr]];
        /*
         此方法参数
         1. 要上传的[二进制数据]
         2. 对应后台处理文件的[字段"files"]（根据后台定义的字段名来）
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if(showLoading){
            [[WPLoadView shared] closeLoadView];
        }
        
        NSDictionary * dic = [((NSData *)responseObject) mj_toDistionary];
        MJBaseModel *model = [MJBaseModel yy_modelWithDictionary:dic];
        if(model.code == 200){
            success(model);
        }else{
            [RoyHud showToast:model.msg];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if(showLoading){
            [[WPLoadView shared] closeLoadView];
        }
        
        failure(error);

    }];

    
}
- (void)postImg:(NSString *)url
         params:(id)params
       imageArr:(NSMutableArray *)imageArr
       callback:(void(^)(id obj, NSError *error))callback {
    
}

@end
